package com.tecent.weixin.mp.bean;

import com.tecent.weixin.utils.WeChatUtils;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cqd on 2015-09-10.
 * 调用统一支付入口成功后，返回页面激活客户端的数据bean定义
 */
public class PrePayData {


    public void setPkg(String pkg) {
        this.pkg = this.pkg+pkg;
        attributes.put("appId",this.appId);
        attributes.put("timeStamp",this.timeStamp);
        attributes.put("nonceStr",this.nonceStr);
        attributes.put("package",this.pkg);
        attributes.put("signType",this.signType);
       this.paySign= generatePaySign(attributes);
    }
    public String appId= MpConfigure.getAppid();
    public String timeStamp="1395712654";
    public String nonceStr= WeChatUtils.getRandomStringByLength(32);
    public String pkg="prepay_id=";
    public String signType="MD5";
    public String paySign;




    public Map<String,String> attributes=new HashMap<String, String>();

    public String generatePaySign(Map<String, String> attribute) {
        if(attribute.size()==0&&attribute==null)return null;
        String [] list= new String[attribute.size()];
        int k=0;
        for (Map.Entry<String, String> data : attribute.entrySet()) {
            list[k]=data.getKey();
            k++;
        }
        Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
        StringBuffer bf = new StringBuffer();
        for(int j=0;j<list.length;j++){
            String key=list[j];
            String value=attribute.get(key);
            if(value!=null){
                bf.append(key + "=" +value + "&");
            }
        }
        //  bf.deleteCharAt(bf.lastIndexOf("&"));
        bf.append("key=" + MpConfigure.getKey());

        return DigestUtils.md5Hex(bf.toString()).toUpperCase();
    }
}
